<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Go语言基础之反射 | 小狐档案库</title>
    <meta name="generator" content="VuePress 1.8.2">
    <link rel="icon" href="/favicon.ico">
    <meta name="description" content="学习资料">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.0c36f186.css" as="style"><link rel="preload" href="/assets/js/app.7029ddab.js" as="script"><link rel="preload" href="/assets/js/3.ebaa3085.js" as="script"><link rel="preload" href="/assets/js/1.8ce67e8c.js" as="script"><link rel="preload" href="/assets/js/28.f308f8ab.js" as="script"><link rel="prefetch" href="/assets/js/10.15c1f9c8.js"><link rel="prefetch" href="/assets/js/11.dc2fbddf.js"><link rel="prefetch" href="/assets/js/12.26ab1f36.js"><link rel="prefetch" href="/assets/js/13.6e1d4dbc.js"><link rel="prefetch" href="/assets/js/14.0cd48e80.js"><link rel="prefetch" href="/assets/js/15.74a9f029.js"><link rel="prefetch" href="/assets/js/16.24ef3382.js"><link rel="prefetch" href="/assets/js/17.c8a9bd0f.js"><link rel="prefetch" href="/assets/js/18.fbd494c2.js"><link rel="prefetch" href="/assets/js/19.f9a0df71.js"><link rel="prefetch" href="/assets/js/20.e6d0df38.js"><link rel="prefetch" href="/assets/js/21.932645cc.js"><link rel="prefetch" href="/assets/js/22.d6027dce.js"><link rel="prefetch" href="/assets/js/23.53bce141.js"><link rel="prefetch" href="/assets/js/24.ed3b8b64.js"><link rel="prefetch" href="/assets/js/25.ed88877e.js"><link rel="prefetch" href="/assets/js/26.f5ad24d5.js"><link rel="prefetch" href="/assets/js/27.64ad45b4.js"><link rel="prefetch" href="/assets/js/29.4d95742d.js"><link rel="prefetch" href="/assets/js/30.0a867de0.js"><link rel="prefetch" href="/assets/js/31.f12def86.js"><link rel="prefetch" href="/assets/js/32.6b4fd8b7.js"><link rel="prefetch" href="/assets/js/33.4bb2aa9c.js"><link rel="prefetch" href="/assets/js/34.013e731c.js"><link rel="prefetch" href="/assets/js/35.6b263ef8.js"><link rel="prefetch" href="/assets/js/36.06acf3cc.js"><link rel="prefetch" href="/assets/js/37.fe72c29c.js"><link rel="prefetch" href="/assets/js/38.9b4e0bd6.js"><link rel="prefetch" href="/assets/js/39.0cde0408.js"><link rel="prefetch" href="/assets/js/4.9b5650bb.js"><link rel="prefetch" href="/assets/js/40.56bda9a8.js"><link rel="prefetch" href="/assets/js/41.007ae34c.js"><link rel="prefetch" href="/assets/js/42.bdaf414b.js"><link rel="prefetch" href="/assets/js/43.78d32d4e.js"><link rel="prefetch" href="/assets/js/44.a10cf8a5.js"><link rel="prefetch" href="/assets/js/45.19e14721.js"><link rel="prefetch" href="/assets/js/46.57ebcf06.js"><link rel="prefetch" href="/assets/js/47.9a513ffe.js"><link rel="prefetch" href="/assets/js/48.245b165a.js"><link rel="prefetch" href="/assets/js/49.fab43655.js"><link rel="prefetch" href="/assets/js/5.a16ef7f8.js"><link rel="prefetch" href="/assets/js/50.48c191fd.js"><link rel="prefetch" href="/assets/js/51.28a94b0e.js"><link rel="prefetch" href="/assets/js/52.e783fbf9.js"><link rel="prefetch" href="/assets/js/53.2f0e960e.js"><link rel="prefetch" href="/assets/js/54.577ff54e.js"><link rel="prefetch" href="/assets/js/55.4bb99598.js"><link rel="prefetch" href="/assets/js/56.e820e954.js"><link rel="prefetch" href="/assets/js/57.0cea0cfa.js"><link rel="prefetch" href="/assets/js/58.e31cfcd0.js"><link rel="prefetch" href="/assets/js/59.458ab168.js"><link rel="prefetch" href="/assets/js/6.7da424ba.js"><link rel="prefetch" href="/assets/js/60.e9caace2.js"><link rel="prefetch" href="/assets/js/61.0b61afdb.js"><link rel="prefetch" href="/assets/js/62.c240acab.js"><link rel="prefetch" href="/assets/js/63.71cd2a97.js"><link rel="prefetch" href="/assets/js/64.977ea29b.js"><link rel="prefetch" href="/assets/js/65.79b2d62a.js"><link rel="prefetch" href="/assets/js/66.8da69071.js"><link rel="prefetch" href="/assets/js/67.fdc57d7e.js"><link rel="prefetch" href="/assets/js/68.d43eabe9.js"><link rel="prefetch" href="/assets/js/7.6e92edd1.js"><link rel="prefetch" href="/assets/js/8.2389170b.js"><link rel="prefetch" href="/assets/js/9.77841f24.js">
    <link rel="stylesheet" href="/assets/css/0.styles.0c36f186.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container" data-v-1156296a><div data-v-1156296a><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-1156296a data-v-1156296a><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-4e82dffc data-v-1156296a data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>小狐档案库</h3> <p class="description" data-v-4e82dffc data-v-4e82dffc>学习资料</p> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div class="hide" data-v-1156296a><header class="navbar" data-v-1156296a><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="小狐档案库" class="logo"> <span class="site-name">小狐档案库</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-1156296a></div> <aside class="sidebar" data-v-1156296a><div class="personal-info-wrapper" data-v-828910c6 data-v-1156296a><img src="/avatar.jpg" alt="author-avatar" class="personal-img" data-v-828910c6> <h3 class="name" data-v-828910c6>
    小狐
  </h3> <div class="num" data-v-828910c6><div data-v-828910c6><h3 data-v-828910c6>58</h3> <h6 data-v-828910c6>Articles</h6></div> <div data-v-828910c6><h3 data-v-828910c6>20</h3> <h6 data-v-828910c6>Tags</h6></div></div> <ul class="social-links" data-v-828910c6></ul> <hr data-v-828910c6></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav> <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>go语言学习</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading open"><span>go语言基础学习</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/blogs/GO/go/1_go_env.html" class="sidebar-link">Go环境安装配置</a></li><li><a href="/blogs/GO/go/2_go_datatype.html" class="sidebar-link">GO基础-基本数据类型</a></li><li><a href="/blogs/GO/go/3_go_var_const.html" class="sidebar-link">Go基础-变量和常量</a></li><li><a href="/blogs/GO/go/5_go_operation.html" class="sidebar-link">GO语言基础之运算符</a></li><li><a href="/blogs/GO/go/24_go_fmt.html" class="sidebar-link">Go语言fmt.Printf使用指南</a></li><li><a href="/blogs/GO/go/25_go_flag.html" class="sidebar-link">Go语言fmt.Printf使用指南</a></li><li><a href="/blogs/GO/go/6_go_array.html" class="sidebar-link">Go语言基础之数组</a></li><li><a href="/blogs/GO/go/7_go_slice.html" class="sidebar-link">Go语言基础之切片</a></li><li><a href="/blogs/GO/go/8_go_map.html" class="sidebar-link">Go语言基础之map</a></li><li><a href="/blogs/GO/go/9_go_pointer.html" class="sidebar-link">Go语言基础之指针</a></li><li><a href="/blogs/GO/go/10_go_func.html" class="sidebar-link">Go语言基础之函数</a></li><li><a href="/blogs/GO/go/11_go_struct.html" class="sidebar-link">Go语言基础之结构体</a></li><li><a href="/blogs/GO/go/12_go_interface.html" class="sidebar-link">Go语言基础之接口</a></li><li><a href="/blogs/GO/go/26_go_reflect.html" aria-current="page" class="active sidebar-link">Go语言基础之反射</a></li><li><a href="/blogs/GO/go/13_go_package.html" class="sidebar-link">Go语言基础之包(package)</a></li><li><a href="/blogs/GO/go/14_go_channel_lock.html" class="sidebar-link">Go语言中的并发编程</a></li><li><a href="/blogs/GO/go/15_go_socket_udp_tcp.html" class="sidebar-link">Go语言基础之网络编程</a></li><li><a href="/blogs/GO/go/16_go_net_http.html" class="sidebar-link">Go语言基础之net/http介绍</a></li><li><a href="/blogs/GO/go/23_go_Context.html" class="sidebar-link">Go标准库Context</a></li><li><a href="/blogs/GO/go/17_go_test.html" class="sidebar-link">Go语言基础之单元测试</a></li><li><a href="/blogs/GO/go/18_go_mod.html" class="sidebar-link">Go语言基础之依赖管理</a></li><li><a href="/blogs/GO/go/19_go_time.html" class="sidebar-link">Go语言基础之time包</a></li><li><a href="/blogs/GO/go/20_go_strconv.html" class="sidebar-link">Go语言内置包之strconv</a></li><li><a href="/blogs/GO/go/22_go_http_template_1.html" class="sidebar-link">Go语言标准库之http/template</a></li></ul></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gin</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>数据库操作</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gorm</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gorm</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>NoSql</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>消息队列</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>go三方库</span> <span class="arrow right"></span></p> <!----></section></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-4e82dffc data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>Go语言基础之反射</h3> <!----> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div data-v-1156296a><main class="page"><section><div class="page-title"><h1 class="title">Go语言基础之反射</h1> <div data-v-1ff7123e><i class="iconfont reco-account" data-v-1ff7123e><span data-v-1ff7123e>小狐</span></i> <i class="iconfont reco-date" data-v-1ff7123e><span data-v-1ff7123e>9/5/2021</span></i> <!----> <i class="tags iconfont reco-tag" data-v-1ff7123e><span class="tag-item" data-v-1ff7123e>GO</span></i></div></div> <div class="theme-reco-content content__default"><h1 id="go语言基础之反射"><a href="#go语言基础之反射" class="header-anchor">#</a> Go语言基础之反射</h1> <p>本文介绍了Go语言反射的意义和基本使用。</p> <h1 id="变量的内在机制"><a href="#变量的内在机制" class="header-anchor">#</a> 变量的内在机制</h1> <p>Go语言中的变量是分为两部分的:</p> <ul><li>类型信息：预先定义好的元信息。</li> <li>值信息：程序运行过程中可动态变化的。</li></ul> <h1 id="反射介绍"><a href="#反射介绍" class="header-anchor">#</a> 反射介绍</h1> <p>反射是指在程序运行期对程序本身进行访问和修改的能力。程序在编译时，变量被转换为内存地址，变量名不会被编译器写入到可执行部分。在运行程序时，程序无法获取自身的信息。</p> <p>支持反射的语言可以在程序编译期将变量的反射信息，如字段名称、类型信息、结构体信息等整合到可执行文件中，并给程序提供接口访问反射信息，这样就可以在程序运行期获取类型的反射信息，并且有能力修改它们。</p> <p>Go程序在运行期使用reflect包访问程序的反射信息。</p> <p>在上一篇博客中我们介绍了空接口。 空接口可以存储任意类型的变量，那我们如何知道这个空接口保存的数据是什么呢？ 反射就是在运行时动态的获取一个变量的类型信息和值信息。</p> <h1 id="reflect包"><a href="#reflect包" class="header-anchor">#</a> reflect包</h1> <p>在Go语言的反射机制中，任何接口值都由是<code>一个具体类型</code>和<code>具体类型的值</code>两部分组成的(我们在上一篇接口的博客中有介绍相关概念)。 在Go语言中反射的相关功能由内置的reflect包提供，任意接口值在反射中都可以理解为由<code>reflect.Type</code>和<code>reflect.Value</code>两部分组成，并且reflect包提供了<code>reflect.TypeOf</code>和<code>reflect.ValueOf</code>两个函数来获取任意对象的Value和Type。</p> <h2 id="typeof"><a href="#typeof" class="header-anchor">#</a> TypeOf</h2> <p>在Go语言中，使用<code>reflect.TypeOf()</code>函数可以获得任意值的类型对象（reflect.Type），程序通过类型对象可以访问任意值的类型信息。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;reflect&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">reflectType</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	v <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">TypeOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type:%v\n&quot;</span><span class="token punctuation">,</span> v<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> a <span class="token builtin">float32</span> <span class="token operator">=</span> <span class="token number">3.14</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment">// type:float32</span>
	<span class="token keyword">var</span> b <span class="token builtin">int64</span> <span class="token operator">=</span> <span class="token number">100</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span> <span class="token comment">// type:int64</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><h3 id="type-name和type-kind"><a href="#type-name和type-kind" class="header-anchor">#</a> type name和type kind</h3> <p>在反射中关于类型还划分为两种：<code>类型（Type）</code>和<code>种类（Kind）</code>。因为在Go语言中我们可以使用type关键字构造很多自定义类型，而<code>种类（Kind）</code>就是指底层的类型，但在反射中，当需要区分指针、结构体等大品种的类型时，就会用到<code>种类（Kind）</code>。 举个例子，我们定义了两个指针类型和两个结构体类型，通过反射查看它们的类型和种类。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;reflect&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> myInt <span class="token builtin">int64</span>

<span class="token keyword">func</span> <span class="token function">reflectType</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	t <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">TypeOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type:%v kind:%v\n&quot;</span><span class="token punctuation">,</span> t<span class="token punctuation">.</span><span class="token function">Name</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> t<span class="token punctuation">.</span><span class="token function">Kind</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> a <span class="token operator">*</span><span class="token builtin">float32</span> <span class="token comment">// 指针</span>
	<span class="token keyword">var</span> b myInt    <span class="token comment">// 自定义类型</span>
	<span class="token keyword">var</span> c <span class="token builtin">rune</span>     <span class="token comment">// 类型别名</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment">// type: kind:ptr</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span> <span class="token comment">// type:myInt kind:int64</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span> <span class="token comment">// type:int32 kind:int32</span>

	<span class="token keyword">type</span> person <span class="token keyword">struct</span> <span class="token punctuation">{</span>
		name <span class="token builtin">string</span>
		age  <span class="token builtin">int</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">type</span> book <span class="token keyword">struct</span><span class="token punctuation">{</span> title <span class="token builtin">string</span> <span class="token punctuation">}</span>
	<span class="token keyword">var</span> d <span class="token operator">=</span> person<span class="token punctuation">{</span>
		name<span class="token punctuation">:</span> <span class="token string">&quot;沙河小王子&quot;</span><span class="token punctuation">,</span>
		age<span class="token punctuation">:</span>  <span class="token number">18</span><span class="token punctuation">,</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">var</span> e <span class="token operator">=</span> book<span class="token punctuation">{</span>title<span class="token punctuation">:</span> <span class="token string">&quot;《跟小王子学Go语言》&quot;</span><span class="token punctuation">}</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span> <span class="token comment">// type:person kind:struct</span>
	<span class="token function">reflectType</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token comment">// type:book kind:struct</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br></div></div><p>Go语言的反射中像数组、切片、Map、指针等类型的变量，它们的<code>.Name()</code>都是返回<code>空</code>。</p> <p>在<code>reflect</code>包中定义的Kind类型如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> Kind <span class="token builtin">uint</span>
<span class="token keyword">const</span> <span class="token punctuation">(</span>
    Invalid Kind <span class="token operator">=</span> <span class="token boolean">iota</span>  <span class="token comment">// 非法类型</span>
    Bool                 <span class="token comment">// 布尔型</span>
    Int                  <span class="token comment">// 有符号整型</span>
    Int8                 <span class="token comment">// 有符号8位整型</span>
    Int16                <span class="token comment">// 有符号16位整型</span>
    Int32                <span class="token comment">// 有符号32位整型</span>
    Int64                <span class="token comment">// 有符号64位整型</span>
    Uint                 <span class="token comment">// 无符号整型</span>
    Uint8                <span class="token comment">// 无符号8位整型</span>
    Uint16               <span class="token comment">// 无符号16位整型</span>
    Uint32               <span class="token comment">// 无符号32位整型</span>
    Uint64               <span class="token comment">// 无符号64位整型</span>
    Uintptr              <span class="token comment">// 指针</span>
    Float32              <span class="token comment">// 单精度浮点数</span>
    Float64              <span class="token comment">// 双精度浮点数</span>
    Complex64            <span class="token comment">// 64位复数类型</span>
    Complex128           <span class="token comment">// 128位复数类型</span>
    Array                <span class="token comment">// 数组</span>
    Chan                 <span class="token comment">// 通道</span>
    Func                 <span class="token comment">// 函数</span>
    Interface            <span class="token comment">// 接口</span>
    Map                  <span class="token comment">// 映射</span>
    Ptr                  <span class="token comment">// 指针</span>
    Slice                <span class="token comment">// 切片</span>
    String               <span class="token comment">// 字符串</span>
    Struct               <span class="token comment">// 结构体</span>
    UnsafePointer        <span class="token comment">// 底层指针</span>
<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br></div></div><h2 id="valueof"><a href="#valueof" class="header-anchor">#</a> ValueOf</h2> <p><code>reflect.ValueOf()</code>返回的是<code>reflect.Value</code>类型，其中包含了原始值的值信息。<code>reflect.Value</code>与原始值之间可以互相转换。</p> <p><code>reflect.Value</code>类型提供的获取原始值的方法如下：</p> <table><thead><tr><th style="text-align:center;">方法</th> <th style="text-align:center;">说明</th></tr></thead> <tbody><tr><td style="text-align:center;">Interface() interface {}</td> <td style="text-align:center;">将值以 interface{} 类型返回，可以通过类型断言转换为指定类型</td></tr> <tr><td style="text-align:center;">Int() int64</td> <td style="text-align:center;">将值以 int 类型返回，所有有符号整型均可以此方式返回</td></tr> <tr><td style="text-align:center;">Uint() uint64</td> <td style="text-align:center;">将值以 uint 类型返回，所有无符号整型均可以此方式返回</td></tr> <tr><td style="text-align:center;">Float() float64</td> <td style="text-align:center;">将值以双精度（float64）类型返回，所有浮点数（float32、float64）均可以此方式返回</td></tr> <tr><td style="text-align:center;">Bool() bool</td> <td style="text-align:center;">将值以 bool 类型返回</td></tr> <tr><td style="text-align:center;">Bytes() []bytes</td> <td style="text-align:center;">将值以字节数组 []bytes 类型返回</td></tr> <tr><td style="text-align:center;">String() string</td> <td style="text-align:center;">将值以字符串类型返回</td></tr></tbody></table> <h3 id="通过反射获取值"><a href="#通过反射获取值" class="header-anchor">#</a> 通过反射获取值</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">reflectValue</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	v <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	k <span class="token operator">:=</span> v<span class="token punctuation">.</span><span class="token function">Kind</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">switch</span> k <span class="token punctuation">{</span>
	<span class="token keyword">case</span> reflect<span class="token punctuation">.</span>Int64<span class="token punctuation">:</span>
		<span class="token comment">// v.Int()从反射中获取整型的原始值，然后通过int64()强制类型转换</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type is int64, value is %d\n&quot;</span><span class="token punctuation">,</span> <span class="token function">int64</span><span class="token punctuation">(</span>v<span class="token punctuation">.</span><span class="token function">Int</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">case</span> reflect<span class="token punctuation">.</span>Float32<span class="token punctuation">:</span>
		<span class="token comment">// v.Float()从反射中获取浮点型的原始值，然后通过float32()强制类型转换</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type is float32, value is %f\n&quot;</span><span class="token punctuation">,</span> <span class="token function">float32</span><span class="token punctuation">(</span>v<span class="token punctuation">.</span><span class="token function">Float</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">case</span> reflect<span class="token punctuation">.</span>Float64<span class="token punctuation">:</span>
		<span class="token comment">// v.Float()从反射中获取浮点型的原始值，然后通过float64()强制类型转换</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type is float64, value is %f\n&quot;</span><span class="token punctuation">,</span> <span class="token function">float64</span><span class="token punctuation">(</span>v<span class="token punctuation">.</span><span class="token function">Float</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> a <span class="token builtin">float32</span> <span class="token operator">=</span> <span class="token number">3.14</span>
	<span class="token keyword">var</span> b <span class="token builtin">int64</span> <span class="token operator">=</span> <span class="token number">100</span>
	<span class="token function">reflectValue</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment">// type is float32, value is 3.140000</span>
	<span class="token function">reflectValue</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span> <span class="token comment">// type is int64, value is 100</span>
	<span class="token comment">// 将int类型的原始值转换为reflect.Value类型</span>
	c <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;type c :%T\n&quot;</span><span class="token punctuation">,</span> c<span class="token punctuation">)</span> <span class="token comment">// type c :reflect.Value</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br></div></div><h3 id="通过反射设置变量的值"><a href="#通过反射设置变量的值" class="header-anchor">#</a> 通过反射设置变量的值</h3> <p>想要在函数中通过反射修改变量的值，需要注意函数参数传递的是值拷贝，必须传递变量地址才能修改变量值。而反射中使用专有的<code>Elem()</code>方法来获取指针对应的值。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;reflect&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">reflectSetValue1</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	v <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	<span class="token keyword">if</span> v<span class="token punctuation">.</span><span class="token function">Kind</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> reflect<span class="token punctuation">.</span>Int64 <span class="token punctuation">{</span>
		v<span class="token punctuation">.</span><span class="token function">SetInt</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span> <span class="token comment">//修改的是副本，reflect包会引发panic</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">reflectSetValue2</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	v <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	<span class="token comment">// 反射中使用 Elem()方法获取指针对应的值</span>
	<span class="token keyword">if</span> v<span class="token punctuation">.</span><span class="token function">Elem</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Kind</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> reflect<span class="token punctuation">.</span>Int64 <span class="token punctuation">{</span>
		v<span class="token punctuation">.</span><span class="token function">Elem</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">SetInt</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> a <span class="token builtin">int64</span> <span class="token operator">=</span> <span class="token number">100</span>
	<span class="token comment">// reflectSetValue1(a) //panic: reflect: reflect.Value.SetInt using unaddressable value</span>
	<span class="token function">reflectSetValue2</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>a<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br></div></div><h3 id="isnil-和isvalid"><a href="#isnil-和isvalid" class="header-anchor">#</a> isNil()和isValid()</h3> <h4 id="isnil"><a href="#isnil" class="header-anchor">#</a> isNil()</h4> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>v Value<span class="token punctuation">)</span> <span class="token function">IsNil</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>IsNil()</code>报告v持有的值是否为nil。v持有的值的分类必须是通道、函数、接口、映射、指针、切片之一；否则IsNil函数会导致panic。</p> <h4 id="isvalid"><a href="#isvalid" class="header-anchor">#</a> isValid()</h4> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>v Value<span class="token punctuation">)</span> <span class="token function">IsValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>IsValid()</code>返回v是否持有一个值。如果v是Value零值会返回假，此时v除了IsValid、String、Kind之外的方法都会导致panic。</p> <h4 id="举个例子"><a href="#举个例子" class="header-anchor">#</a> 举个例子</h4> <p><code>IsNil()</code>常被用于判断指针是否为空；<code>IsValid()</code>常被用于判定返回值是否有效。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">// *int类型空指针</span>
	<span class="token keyword">var</span> a <span class="token operator">*</span><span class="token builtin">int</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;var a *int IsNil:&quot;</span><span class="token punctuation">,</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">IsNil</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token comment">// nil值</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;nil IsValid:&quot;</span><span class="token punctuation">,</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span><span class="token boolean">nil</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">IsValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token comment">// 实例化一个匿名结构体</span>
	b <span class="token operator">:=</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token comment">// 尝试从结构体中查找&quot;abc&quot;字段</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;不存在的结构体成员:&quot;</span><span class="token punctuation">,</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">FieldByName</span><span class="token punctuation">(</span><span class="token string">&quot;abc&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">IsValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token comment">// 尝试从结构体中查找&quot;abc&quot;方法</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;不存在的结构体方法:&quot;</span><span class="token punctuation">,</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">MethodByName</span><span class="token punctuation">(</span><span class="token string">&quot;abc&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">IsValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token comment">// map</span>
	c <span class="token operator">:=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token comment">// 尝试从map中查找一个不存在的键</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;map中不存在的键：&quot;</span><span class="token punctuation">,</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">MapIndex</span><span class="token punctuation">(</span>reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span><span class="token string">&quot;娜扎&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">IsValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><h1 id="结构体反射"><a href="#结构体反射" class="header-anchor">#</a> 结构体反射</h1> <h2 id="与结构体相关的方法"><a href="#与结构体相关的方法" class="header-anchor">#</a> 与结构体相关的方法</h2> <p>任意值通过<code>reflect.TypeOf()</code>获得反射对象信息后，如果它的类型是结构体，可以通过反射值对象（<code>reflect.Type</code>）的<code>NumField()</code>和<code>Field()</code>方法获得结构体成员的详细信息。</p> <p><code>reflect.Type</code>中与获取结构体成员相关的的方法如下表所示。</p> <table><thead><tr><th style="text-align:center;">方法</th> <th style="text-align:center;">说明</th></tr></thead> <tbody><tr><td style="text-align:center;">Field(i int) StructField</td> <td style="text-align:center;">根据索引，返回索引对应的结构体字段的信息。</td></tr> <tr><td style="text-align:center;">NumField() int</td> <td style="text-align:center;">返回结构体成员字段数量。</td></tr> <tr><td style="text-align:center;">FieldByName(name string) (StructField, bool)</td> <td style="text-align:center;">根据给定字符串返回字符串对应的结构体字段的信息。</td></tr> <tr><td style="text-align:center;">FieldByIndex(index []int) StructField</td> <td style="text-align:center;">多层成员访问时，根据 []int 提供的每个结构体的字段索引，返回字段的信息。</td></tr> <tr><td style="text-align:center;">FieldByNameFunc(match func(string) bool) (StructField,bool)</td> <td style="text-align:center;">根据传入的匹配函数匹配需要的字段。</td></tr> <tr><td style="text-align:center;">NumMethod() int</td> <td style="text-align:center;">返回该类型的方法集中方法的数目</td></tr> <tr><td style="text-align:center;">Method(int) Method</td> <td style="text-align:center;">返回该类型方法集中的第i个方法</td></tr> <tr><td style="text-align:center;">MethodByName(string)(Method, bool)</td> <td style="text-align:center;">根据方法名返回该类型方法集中的方法</td></tr></tbody></table> <h2 id="structfield类型"><a href="#structfield类型" class="header-anchor">#</a> StructField类型</h2> <p><code>StructField</code>类型用来描述结构体中的一个字段的信息。</p> <p><code>StructField</code>的定义如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> StructField <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    <span class="token comment">// Name是字段的名字。PkgPath是非导出字段的包路径，对导出字段该字段为&quot;&quot;。</span>
    <span class="token comment">// 参见http://golang.org/ref/spec#Uniqueness_of_identifiers</span>
    Name    <span class="token builtin">string</span>
    PkgPath <span class="token builtin">string</span>
    Type      Type      <span class="token comment">// 字段的类型</span>
    Tag       StructTag <span class="token comment">// 字段的标签</span>
    Offset    <span class="token builtin">uintptr</span>   <span class="token comment">// 字段在结构体中的字节偏移量</span>
    Index     <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span>     <span class="token comment">// 用于Type.FieldByIndex时的索引切片</span>
    Anonymous <span class="token builtin">bool</span>      <span class="token comment">// 是否匿名字段</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><h2 id="结构体反射示例"><a href="#结构体反射示例" class="header-anchor">#</a> 结构体反射示例</h2> <p>当我们使用反射得到一个结构体数据之后可以通过索引依次获取其字段信息，也可以通过字段名去获取指定的字段信息。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> student <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	Name  <span class="token builtin">string</span> <span class="token string">`json:&quot;name&quot;`</span>
	Score <span class="token builtin">int</span>    <span class="token string">`json:&quot;score&quot;`</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	stu1 <span class="token operator">:=</span> student<span class="token punctuation">{</span>
		Name<span class="token punctuation">:</span>  <span class="token string">&quot;小王子&quot;</span><span class="token punctuation">,</span>
		Score<span class="token punctuation">:</span> <span class="token number">90</span><span class="token punctuation">,</span>
	<span class="token punctuation">}</span>

	t <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">TypeOf</span><span class="token punctuation">(</span>stu1<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>t<span class="token punctuation">.</span><span class="token function">Name</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> t<span class="token punctuation">.</span><span class="token function">Kind</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// student struct</span>
	<span class="token comment">// 通过for循环遍历结构体的所有字段信息</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> t<span class="token punctuation">.</span><span class="token function">NumField</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		field <span class="token operator">:=</span> t<span class="token punctuation">.</span><span class="token function">Field</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;name:%s index:%d type:%v json tag:%v\n&quot;</span><span class="token punctuation">,</span> field<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> field<span class="token punctuation">.</span>Index<span class="token punctuation">,</span> field<span class="token punctuation">.</span>Type<span class="token punctuation">,</span> field<span class="token punctuation">.</span>Tag<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">&quot;json&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>

	<span class="token comment">// 通过字段名获取指定结构体字段信息</span>
	<span class="token keyword">if</span> scoreField<span class="token punctuation">,</span> ok <span class="token operator">:=</span> t<span class="token punctuation">.</span><span class="token function">FieldByName</span><span class="token punctuation">(</span><span class="token string">&quot;Score&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;name:%s index:%d type:%v json tag:%v\n&quot;</span><span class="token punctuation">,</span> scoreField<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> scoreField<span class="token punctuation">.</span>Index<span class="token punctuation">,</span> scoreField<span class="token punctuation">.</span>Type<span class="token punctuation">,</span> scoreField<span class="token punctuation">.</span>Tag<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">&quot;json&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br></div></div><p>接下来编写一个函数<code>printMethod(s interface{})</code>来遍历打印s包含的方法。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 给student添加两个方法 Study和Sleep(注意首字母大写)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>s student<span class="token punctuation">)</span> <span class="token function">Study</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
	msg <span class="token operator">:=</span> <span class="token string">&quot;好好学习，天天向上。&quot;</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span>
	<span class="token keyword">return</span> msg
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>s student<span class="token punctuation">)</span> <span class="token function">Sleep</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
	msg <span class="token operator">:=</span> <span class="token string">&quot;好好睡觉，快快长大。&quot;</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span>
	<span class="token keyword">return</span> msg
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">printMethod</span><span class="token punctuation">(</span>x <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	t <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">TypeOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
	v <span class="token operator">:=</span> reflect<span class="token punctuation">.</span><span class="token function">ValueOf</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>t<span class="token punctuation">.</span><span class="token function">NumMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> v<span class="token punctuation">.</span><span class="token function">NumMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		methodType <span class="token operator">:=</span> v<span class="token punctuation">.</span><span class="token function">Method</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Type</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;method name:%s\n&quot;</span><span class="token punctuation">,</span> t<span class="token punctuation">.</span><span class="token function">Method</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span>Name<span class="token punctuation">)</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;method:%s\n&quot;</span><span class="token punctuation">,</span> methodType<span class="token punctuation">)</span>
		<span class="token comment">// 通过反射调用方法传递的参数必须是 []reflect.Value 类型</span>
		<span class="token keyword">var</span> args <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>reflect<span class="token punctuation">.</span>Value<span class="token punctuation">{</span><span class="token punctuation">}</span>
		v<span class="token punctuation">.</span><span class="token function">Method</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Call</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br></div></div><h1 id="反射是把双刃剑"><a href="#反射是把双刃剑" class="header-anchor">#</a> 反射是把双刃剑</h1> <p>反射是一个强大并富有表现力的工具，能让我们写出更灵活的代码。但是反射不应该被滥用，原因有以下三个。</p> <ol><li>基于反射的代码是极其脆弱的，反射中的类型错误会在真正运行的时候才会引发panic，那很可能是在代码写完的很长时间之后。</li> <li>大量使用反射的代码通常难以理解。</li> <li>反射的性能低下，基于反射实现的代码通常比正常代码运行速度慢一到两个数量级。</li></ol></div></section> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">2021-9-2: </span> <span class="time">9/3/2021, 6:20:18 PM</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev"><a href="/blogs/GO/go/12_go_interface.html" class="prev">
            Go语言基础之接口
          </a></span> <span class="next"><a href="/blogs/GO/go/13_go_package.html">
            Go语言基础之包(package)
          </a></span></p></div> <div class="comments-wrapper"><!----></div> <ul class="side-bar sub-sidebar-wrapper" style="width:12rem;" data-v-70334359><li class="level-2" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#typeof" class="sidebar-link reco-side-typeof" data-v-70334359>TypeOf</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#type-name和type-kind" class="sidebar-link reco-side-type-name和type-kind" data-v-70334359>type name和type kind</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#valueof" class="sidebar-link reco-side-valueof" data-v-70334359>ValueOf</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#通过反射获取值" class="sidebar-link reco-side-通过反射获取值" data-v-70334359>通过反射获取值</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#通过反射设置变量的值" class="sidebar-link reco-side-通过反射设置变量的值" data-v-70334359>通过反射设置变量的值</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#isnil-和isvalid" class="sidebar-link reco-side-isnil-和isvalid" data-v-70334359>isNil()和isValid()</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#与结构体相关的方法" class="sidebar-link reco-side-与结构体相关的方法" data-v-70334359>与结构体相关的方法</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#structfield类型" class="sidebar-link reco-side-structfield类型" data-v-70334359>StructField类型</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go/26_go_reflect.html#结构体反射示例" class="sidebar-link reco-side-结构体反射示例" data-v-70334359>结构体反射示例</a></li></ul></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><!----><canvas id="vuepress-canvas-cursor"></canvas></div></div>
    <script src="/assets/js/app.7029ddab.js" defer></script><script src="/assets/js/3.ebaa3085.js" defer></script><script src="/assets/js/1.8ce67e8c.js" defer></script><script src="/assets/js/28.f308f8ab.js" defer></script>
  </body>
</html>
